package installinjava;

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.LayoutStyle.ComponentPlacement;

/**
 * Creates a button panel.
 *
 * @author Gili Tzabari
 */
public class ButtonPanelBuilder
{
	private boolean back = false;
	private boolean next = false;
	private boolean cancel = false;

	/**
	 * Adds a <code>back</code> button.
	 *
	 * @return the ButtonPanelBuilder
	 */
	public ButtonPanelBuilder addBack()
	{
		this.back = true;
		return this;
	}

	/**
	 * Adds a <code>next</code> button.
	 *
	 * @return the ButtonPanelBuilder
	 */
	public ButtonPanelBuilder addNext()
	{
		this.next = true;
		return this;
	}

	/**
	 * Adds a <code>cancel</code> button.
	 *
	 * @return the ButtonPanelBuilder
	 */
	public ButtonPanelBuilder addCancel()
	{
		this.cancel = true;
		return this;
	}

	/**
	 * Builds a button panel.
	 *
	 * @return the button panel
	 */
	public JPanel build()
	{
		JPanel result = new JPanel();
		GroupLayout layout = new GroupLayout(result);
		result.setLayout(layout);
		GroupLayout.SequentialGroup sequential = layout.createSequentialGroup().
			addContainerGap(GroupLayout.DEFAULT_SIZE, Integer.MAX_VALUE);
		GroupLayout.ParallelGroup parallel = layout.createParallelGroup();
		List<Component> components = new ArrayList<Component>();
		if (back)
		{
			JButton backButton = new JButton("< Back");
			backButton.setMnemonic('B');
			sequential = sequential.addComponent(backButton);
			parallel = parallel.addComponent(backButton);
			components.add(backButton);
		}
		if (next)
		{
			JButton nextButton = new JButton("Next >");
			nextButton.setMnemonic('N');
			sequential = sequential.addComponent(nextButton);
			parallel = parallel.addComponent(nextButton);
			components.add(nextButton);
		}
		if (back || next)
			sequential = sequential.addPreferredGap(ComponentPlacement.UNRELATED);
		if (cancel)
		{
			JButton cancelButton = new JButton("Cancel");
			sequential = sequential.addComponent(cancelButton);
			parallel = parallel.addComponent(cancelButton);
			components.add(cancelButton);
		}
		layout.setHorizontalGroup(sequential.addContainerGap());
		layout.setVerticalGroup(parallel);
		layout.linkSize(components.toArray(new Component[0]));
		return result;
	}
}
